import { _pick, reduceToObject } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker";
import pageMW from "../../middleware/pager";
import {
  listNormalBrandSpokesmanWithUsersByBrandID,
  updateBrandSpokesman,
} from "../../service/brandSpokesmanService";
import { listAggsToUserRecentNewses } from "../../service/userPvLogService";
const router = createBrandApiMWRouter();

// 获取品牌代言人列表
router.get(
  "brand-spokesmans",
  "/brd/:brandId/spokesmans",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { brandId } = ctx.params;
    let { keyword } = ctx.query;
    const { userId, limit, offset, ts } = ctx;

    const { total, items } = await listNormalBrandSpokesmanWithUsersByBrandID(
      { brandId, keyword },
      {
        limit,
        offset,
        ts,
      }
    );
    const followerRecentNews = await listAggsToUserRecentNewses(
      items.map((it) => it.userId)
    );
    const recentNewsMap = reduceToObject(
      followerRecentNews,
      (o) => o.userId,
      (o) => o.latestTime
    );

    ctx.body = {
      total,
      rows: items.map((it) => ({
        recentNews: recentNewsMap[it.userId],
        ..._pick(
          it,
          "brandSpokesmanId",
          "aliasName",
          "endorseActivityCount",
          "saleAmount",
          "spokesmanUserNickName",
          "spokesmanUserPic",
          "fansCount"
        ),
      })),
    };
  }
);

// // todo: 邀请品牌代言人
// router.post("/brd/:brandId/spokesman", async (ctx: AppCTX, next) => {
//   const { brandId } = ctx.params;
//   const { mobile } = ctx.request.body;
//   const { userId } = ctx;

//   //1 增加判断如果该手机号对应的用户已经是代言人,报错
//   //2 userId(操作人不是品牌代言人),报错

//   ctx.body = {
//     brandId,
//     userId, //操作人
//     mobile,
//     spokesmanId: (101).toString(),
//   };
// });

// 移除品牌代言人(暂时不用)
// router.delete("/brd/:brandId/spokesman/:spokesmanId", async (ctx: AppCTX, next) => {
//   const { brandId, spokesmanId } = ctx.params;
//   const { userId } = ctx;
//   //1 userId(操作人不是品牌代言人),报错

//   ctx.body = {
//     brandId,
//     userId, //操作人
//     spokesmanId,
//   };
// });

// 备注品牌代言人名称
router.put(
  "/brd/:brandId/spokesman/alias/:brandSpokesmanId",
  async (ctx: AppCTX, next) => {
    const { brandId, brandSpokesmanId } = ctx.params;
    const { aliasName } = ctx.request.body;
    const { userId } = ctx;
    //1 userId(操作人不是代言人),报错

    const brandSpokesman = await updateBrandSpokesman({
      brandSpokesmanId,
      aliasName,
    });

    ctx.body = {
      ..._pick(brandSpokesman, "brandSpokesmanId", "brandId", "aliasName"),
    };
  }
);

export default router;
